package com.okcl.manager.service.impl;

import com.okcl.common.exception.BusinessException;
import com.okcl.manager.mapper.SysMenuMapper;
import com.okcl.manager.mapper.SysRoleMenuMapper;
import com.okcl.manager.service.SysMenuService;
import com.okcl.manager.utils.MenuHelper;
import com.okcl.model.entity.system.SysMenu;
import com.okcl.model.vo.common.ResultCodeEnum;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Resource
    private SysMenuMapper sysMenuMapper;
    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;

    /**
     * 查询所有菜单
     *
     * @return
     */
    @Override
    public List<SysMenu> selectMenuList() {
        List<SysMenu> sysMenuList = sysMenuMapper.selectMenuList();
        if (CollectionUtils.isEmpty(sysMenuList)) {
            return null;
        }
        return MenuHelper.buildTree(sysMenuList);
    }

    /**
     * 添加菜单
     *
     * @param sysMenu
     */
    @Override
    @Transactional
    public void addMenu(SysMenu sysMenu) {
        int i = sysMenuMapper.addMenu(sysMenu);
        if (i <= 0) {
            throw new BusinessException(ResultCodeEnum.FAILURE);
        }
        //新添加子菜单把父菜单isHalf状态改为1
        setSysMenuParentIdIsHalf(sysMenu);
    }

    /**
     * 修改菜单
     *
     * @param sysMenu
     */
    @Override
    @Transactional
    public void editMenu(SysMenu sysMenu) {
        int i = sysMenuMapper.editMenu(sysMenu);
        if (i <= 0) {
            throw new BusinessException(ResultCodeEnum.FAILURE);
        }
    }

    /**
     * 删除菜单
     *
     * @param id
     */
    @Override
    @Transactional
    public void deleteMenu(Long id) {
        if (sysMenuMapper.selectMenuIsExists(id) > 0) {
            throw new BusinessException(500, "该菜单下有子菜单，请先删除子菜单");
        }
        sysMenuMapper.deleteMenu(id);
    }

    /**
     * 将父菜单的全开状态改为半开
     *
     * @param sysMenu
     */
    private void setSysMenuParentIdIsHalf(SysMenu sysMenu) {
        SysMenu parentMenu = sysMenuMapper.queryMenuById(sysMenu.getParentId());
        if (parentMenu != null) {
            //将父节点的parentId设置为半选中
            sysRoleMenuMapper.updateParentIdIsHalf(parentMenu.getId());
            //递归调用
            setSysMenuParentIdIsHalf(parentMenu);
        }
    }
}
